import sys
import pyperclip
import os
import json
import logging
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, 
                            QMessageBox, QDialog, QFormLayout, QHeaderView, QMenu, QInputDialog,
                            QToolBar, QStatusBar, QFrame, QSizePolicy, QProgressBar, QTabWidget,
                            QComboBox, QCheckBox, QSystemTrayIcon, QFileDialog)
from PyQt6.QtCore import Qt, pyqtSignal, QSize, QTimer, QSettings
from PyQt6.QtGui import QAction, QIcon, QFont, QColor, QPalette, QPixmap

from database import DatabaseManager as Database
from dotenv import load_dotenv
from password_generator import PasswordGenerator
from password_generator_dialog import PasswordGeneratorDialog
from settings_dialog import SettingsDialog
from style_manager import StyleManager

class PasswordDialog(QDialog):
    """对话框，用于添加或编辑密码"""
    
    def __init__(self, parent=None, password_id=None, platform=None, username=None, password=None):
        super().__init__(parent)
        self.password_id = password_id
        self.password_generator = PasswordGenerator()
        self.settings = QSettings('PasswordManager', 'Settings')
        self.init_ui(platform, username, password)
        self.apply_styles()
        
    def init_ui(self, platform, username, password):
        self.setWindowTitle("添加新密码" if self.password_id is None else "编辑密码")
        self.setMinimumWidth(450)
        
        main_layout = QVBoxLayout()
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题标签
        title_label = QLabel("添加新密码" if self.password_id is None else "编辑密码")
        title_label.setObjectName("dialogTitle")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        main_layout.addWidget(title_label)
        
        # 分隔线
        line = QFrame()
        line.setFrameShape(QFrame.Shape.HLine)
        line.setFrameShadow(QFrame.Shadow.Sunken)
        line.setObjectName("separator")
        main_layout.addWidget(line)
        
        # 表单布局
        form_layout = QFormLayout()
        form_layout.setSpacing(10)
        form_layout.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
        
        # 平台输入
        platform_label = QLabel("平台:")
        platform_label.setObjectName("formLabel")
        self.platform_edit = QLineEdit(platform if platform else "")
        self.platform_edit.setPlaceholderText("输入平台名称")
        self.platform_edit.setObjectName("formInput")
        form_layout.addRow(platform_label, self.platform_edit)
        
        # 用户名输入
        username_label = QLabel("用户名:")
        username_label.setObjectName("formLabel")
        self.username_edit = QLineEdit(username if username else "")
        self.username_edit.setPlaceholderText("输入用户名")
        self.username_edit.setObjectName("formInput")
        form_layout.addRow(username_label, self.username_edit)
        
        # 密码输入布局
        password_layout = QHBoxLayout()
        
        self.password_edit = QLineEdit(password if password else "")
        self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
        self.password_edit.setPlaceholderText("输入密码")
        self.password_edit.setObjectName("formInput")
        self.password_edit.textChanged.connect(self.update_password_strength)
        password_layout.addWidget(self.password_edit)
        
        # 生成密码按钮
        self.generate_btn = QPushButton("生成")
        self.generate_btn.setObjectName("iconButton")
        self.generate_btn.setToolTip("生成安全密码")
        self.generate_btn.clicked.connect(self.generate_password)
        password_layout.addWidget(self.generate_btn)
        
        form_layout.addRow("密码:", password_layout)
        
        # 密码强度指示器
        strength_layout = QHBoxLayout()
        
        self.strength_progress = QProgressBar()
        self.strength_progress.setRange(0, 100)
        self.strength_progress.setTextVisible(False)
        self.strength_progress.setFixedHeight(8)
        self.strength_progress.setObjectName("strengthProgress")
        strength_layout.addWidget(self.strength_progress)
        
        self.strength_label = QLabel("密码强度")
        self.strength_label.setObjectName("strengthLabel")
        strength_layout.addWidget(self.strength_label)
        
        form_layout.addRow("", strength_layout)
        
        # URL输入
        url_label = QLabel("URL:")
        url_label.setObjectName("formLabel")
        self.url_edit = QLineEdit()
        self.url_edit.setPlaceholderText("输入网站URL（可选）")
        self.url_edit.setObjectName("formInput")
        form_layout.addRow(url_label, self.url_edit)
        
        # 分类输入
        category_label = QLabel("分类:")
        category_label.setObjectName("formLabel")
        self.category_combo = QComboBox()
        self.category_combo.setEditable(True)
        self.category_combo.setObjectName("formInput")
        self.category_combo.addItems(["未分类", "工作", "个人", "金融", "社交媒体", "电子邮件", "购物", "游戏", "其他"])
        form_layout.addRow(category_label, self.category_combo)
        
        # 备注输入
        notes_label = QLabel("备注:")
        notes_label.setObjectName("formLabel")
        self.notes_edit = QLineEdit()
        self.notes_edit.setPlaceholderText("输入备注信息（可选）")
        self.notes_edit.setObjectName("formInput")
        form_layout.addRow(notes_label, self.notes_edit)
        
        main_layout.addLayout(form_layout)
        
        # 密码可见性布局
        password_visibility_layout = QHBoxLayout()
        password_visibility_layout.setContentsMargins(0, 5, 0, 10)
        
        # 显示/隐藏密码按钮
        self.toggle_password_btn = QPushButton("显示密码")
        self.toggle_password_btn.setObjectName("toggleButton")
        self.toggle_password_btn.clicked.connect(self.toggle_password_visibility)
        self.toggle_password_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        password_visibility_layout.addStretch()
        password_visibility_layout.addWidget(self.toggle_password_btn)
        
        main_layout.addLayout(password_visibility_layout)
        
        # 分隔线
        line2 = QFrame()
        line2.setFrameShape(QFrame.Shape.HLine)
        line2.setFrameShadow(QFrame.Shadow.Sunken)
        line2.setObjectName("separator")
        main_layout.addWidget(line2)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.setObjectName("cancelButton")
        self.cancel_btn.clicked.connect(self.reject)
        self.cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        
        self.save_btn = QPushButton("保存")
        self.save_btn.setObjectName("primaryButton")
        self.save_btn.clicked.connect(self.accept)
        self.save_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        
        button_layout.addWidget(self.cancel_btn)
        button_layout.addWidget(self.save_btn)
        
        main_layout.addLayout(button_layout)
        self.setLayout(main_layout)
        
        # 初始化密码强度
        if password:
            self.update_password_strength()
    
    def toggle_password_visibility(self):
        if self.password_edit.echoMode() == QLineEdit.EchoMode.Password:
            self.password_edit.setEchoMode(QLineEdit.EchoMode.Normal)
            self.toggle_password_btn.setText("隐藏密码")
        else:
            self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
            self.toggle_password_btn.setText("显示密码")
    
    def generate_password(self):
        """打开密码生成器对话框"""
        dialog = PasswordGeneratorDialog(self)
        if dialog.exec():
            # 获取生成的密码
            password = dialog.password_edit.text()
            self.password_edit.setText(password)
            self.update_password_strength()
    
    def update_password_strength(self):
        """更新密码强度指示器"""
        password = self.password_edit.text()
        score, strength, suggestions = self.password_generator.check_password_strength(password)
        
        # 更新进度条
        self.strength_progress.setValue(score)
        
        # 设置进度条颜色
        if score < 40:
            self.strength_progress.setStyleSheet("QProgressBar::chunk { background-color: #fa5252; }")
            self.strength_label.setText("弱")
            self.strength_label.setStyleSheet("color: #fa5252;")
        elif score < 60:
            self.strength_progress.setStyleSheet("QProgressBar::chunk { background-color: #ffd43b; }")
            self.strength_label.setText("中")
            self.strength_label.setStyleSheet("color: #ffd43b;")
        elif score < 80:
            self.strength_progress.setStyleSheet("QProgressBar::chunk { background-color: #51cf66; }")
            self.strength_label.setText("强")
            self.strength_label.setStyleSheet("color: #51cf66;")
        else:
            self.strength_progress.setStyleSheet("QProgressBar::chunk { background-color: #40c057; }")
            self.strength_label.setText("非常强")
            self.strength_label.setStyleSheet("color: #40c057;")
    
    def apply_styles(self):
        """应用样式到对话框"""
        self.setStyleSheet("""
            QDialog {
                background-color: #f8f9fa;
                border-radius: 15px;
            }
            
            #dialogTitle {
                font-size: 22px;
                font-weight: bold;
                color: #2c3e50;
                margin-bottom: 15px;
                padding: 5px 0;
            }
            
            #separator {
                background-color: #e9ecef;
                height: 1px;
                margin: 15px 0;
            }
            
            #formLabel {
                font-weight: bold;
                color: #495057;
                font-size: 14px;
            }
            
            #formInput {
                padding: 12px;
                border: 1px solid #ced4da;
                border-radius: 8px;
                background-color: white;
                selection-background-color: #4dabf7;
                color: #495057;
                font-size: 14px;
                transition: all 0.2s ease;
            }
            
            #formInput:focus {
                border: 1px solid #4dabf7;
                box-shadow: 0 0 0 3px rgba(77, 171, 247, 0.25);
            }
            
            #formInput:hover:!focus {
                border-color: #adb5bd;
            }
            
            #formInput::placeholder {
                color: #adb5bd;
            }
            
            #strengthProgress {
                border: none;
                border-radius: 4px;
                background-color: #e9ecef;
            }
            
            #strengthLabel {
                font-weight: bold;
                margin-left: 10px;
                min-width: 60px;
            }
            
            #iconButton {
                background-color: #e9ecef;
                border: 1px solid #ced4da;
                border-radius: 8px;
                padding: 8px 12px;
                color: #495057;
                font-weight: medium;
                transition: all 0.2s ease;
            }
            
            #iconButton:hover {
                background-color: #dee2e6;
                border-color: #adb5bd;
            }
            
            #iconButton:pressed {
                background-color: #ced4da;
            }
            
            #toggleButton {
                background-color: #e9ecef;
                border: 1px solid #ced4da;
                border-radius: 8px;
                padding: 8px 12px;
                color: #495057;
                font-weight: medium;
                transition: all 0.2s ease;
            }
            
            #toggleButton:hover {
                background-color: #dee2e6;
                border-color: #adb5bd;
            }
            
            #toggleButton:pressed {
                background-color: #ced4da;
            }
            
            #primaryButton {
                background-color: #4dabf7;
                color: white;
                border: none;
                border-radius: 8px;
                padding: 10px 20px;
                font-weight: bold;
                font-size: 14px;
                transition: all 0.2s ease;
            }
            
            #primaryButton:hover {
                background-color: #339af0;
                transform: translateY(-1px);
            }
            
            #primaryButton:pressed {
                background-color: #228be6;
                transform: translateY(1px);
            }
            
            #cancelButton {
                background-color: #e9ecef;
                color: #495057;
                border: 1px solid #ced4da;
                border-radius: 8px;
                padding: 10px 20px;
                font-weight: bold;
                font-size: 14px;
                transition: all 0.2s ease;
            }
            
            #cancelButton:hover {
                background-color: #dee2e6;
                border-color: #adb5bd;
                transform: translateY(-1px);
            }
            
            #cancelButton:pressed {
                background-color: #ced4da;
                transform: translateY(1px);
            }
        """)

class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.db = Database()
        self.password_generator = PasswordGenerator()
        self.settings = QSettings('PasswordManager', 'Settings')
        self.style_manager = StyleManager()
        self.init_ui()
        self.load_settings()
        self.apply_theme()
        
        # 设置自动锁定定时器
        self.auto_lock_timer = QTimer(self)
        self.auto_lock_timer.timeout.connect(self.lock_application)
        self.reset_auto_lock_timer()
        
        # 设置剪贴板清除定时器
        self.clipboard_timer = QTimer(self)
        self.clipboard_timer.setSingleShot(True)
        self.clipboard_timer.timeout.connect(self.clear_clipboard)
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("密码管理器")
        self.setMinimumSize(900, 600)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)
        
        # 创建搜索栏
        search_layout = QHBoxLayout()
        
        search_label = QLabel("搜索:")
        search_label.setObjectName("searchLabel")
        search_layout.addWidget(search_label)
        
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("搜索平台、用户名或备注...")
        self.search_edit.setObjectName("searchInput")
        self.search_edit.textChanged.connect(self.filter_passwords)
        search_layout.addWidget(self.search_edit)
        
        # 分类过滤下拉框
        self.category_filter = QComboBox()
        self.category_filter.setObjectName("categoryFilter")
        self.category_filter.addItem("所有分类")
        self.category_filter.addItems(["未分类", "工作", "个人", "金融", "社交媒体", "电子邮件", "购物", "游戏", "其他"])
        self.category_filter.currentTextChanged.connect(self.filter_passwords)
        search_layout.addWidget(self.category_filter)
        
        main_layout.addLayout(search_layout)
        
        # 创建密码表格
        self.table = QTableWidget(0, 6)
        self.table.setHorizontalHeaderLabels(["平台", "用户名", "密码", "URL", "分类", "备注"])
        self.table.setObjectName("passwordTable")
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.table.setAlternatingRowColors(True)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
        self.table.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.show_context_menu)
        self.table.cellDoubleClicked.connect(self.edit_password)
        main_layout.addWidget(self.table)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        self.add_btn = QPushButton("添加密码")
        self.add_btn.setObjectName("primaryButton")
        self.add_btn.clicked.connect(self.add_password)
        self.add_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        button_layout.addWidget(self.add_btn)
        
        self.edit_btn = QPushButton("编辑密码")
        self.edit_btn.setObjectName("secondaryButton")
        self.edit_btn.clicked.connect(self.edit_selected_password)
        self.edit_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        button_layout.addWidget(self.edit_btn)
        
        self.delete_btn = QPushButton("删除密码")
        self.delete_btn.setObjectName("dangerButton")
        self.delete_btn.clicked.connect(self.delete_selected_password)
        self.delete_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        button_layout.addWidget(self.delete_btn)
        
        self.generate_btn = QPushButton("生成密码")
        self.generate_btn.setObjectName("secondaryButton")
        self.generate_btn.clicked.connect(self.show_password_generator)
        self.generate_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        button_layout.addWidget(self.generate_btn)
        
        main_layout.addLayout(button_layout)
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建工具栏
        self.create_toolbar()
        
        # 创建状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage("就绪")
        
        # 加载密码数据
        self.load_passwords()
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        import_action = QAction("导入密码", self)
        import_action.triggered.connect(self.import_passwords)
        file_menu.addAction(import_action)
        
        export_action = QAction("导出密码", self)
        export_action.triggered.connect(self.export_passwords)
        file_menu.addAction(export_action)
        
        file_menu.addSeparator()
        
        settings_action = QAction("设置", self)
        settings_action.triggered.connect(self.show_settings)
        file_menu.addAction(settings_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 工具菜单
        tools_menu = menubar.addMenu("工具")
        
        analyze_action = QAction("密码分析", self)
        analyze_action.triggered.connect(self.analyze_passwords)
        tools_menu.addAction(analyze_action)
        
        generate_action = QAction("密码生成器", self)
        generate_action.triggered.connect(self.show_password_generator)
        tools_menu.addAction(generate_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu("帮助")
        
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def create_toolbar(self):
        """创建工具栏"""
        toolbar = QToolBar()
        toolbar.setMovable(False)
        toolbar.setIconSize(QSize(16, 16))
        self.addToolBar(toolbar)
        
        # 添加工具栏按钮
        add_action = QAction("添加", self)
        add_action.triggered.connect(self.add_password)
        toolbar.addAction(add_action)
        
        edit_action = QAction("编辑", self)
        edit_action.triggered.connect(self.edit_selected_password)
        toolbar.addAction(edit_action)
        
        delete_action = QAction("删除", self)
        delete_action.triggered.connect(self.delete_selected_password)
        toolbar.addAction(delete_action)
        
        toolbar.addSeparator()
        
        generate_action = QAction("生成密码", self)
        generate_action.triggered.connect(self.show_password_generator)
        toolbar.addAction(generate_action)
        
        analyze_action = QAction("分析", self)
        analyze_action.triggered.connect(self.analyze_passwords)
        toolbar.addAction(analyze_action)
        
        toolbar.addSeparator()
        
        settings_action = QAction("设置", self)
        settings_action.triggered.connect(self.show_settings)
        toolbar.addAction(settings_action)
    
    def load_passwords(self):
        """从数据库加载密码"""
        try:
            passwords = self.db.get_all_passwords()
            logging.debug(f"从数据库获取到 {len(passwords)} 条密码记录")
            
            if not passwords:
                self.table.setRowCount(0)
                self.statusBar.showMessage("数据库中没有密码记录")
                return
                
            self.table.setRowCount(len(passwords))
            
            for row, password in enumerate(passwords):
                # 检查密码记录的格式
                logging.debug(f"处理密码记录: {password}")
                
                # 数据库查询返回: id, platform, url, username, password, notes
                # 设置密码ID为用户数据
                id_item = QTableWidgetItem(str(password['platform']))  # 平台名称
                id_item.setData(Qt.ItemDataRole.UserRole, password['id'])  # 密码ID
                self.table.setItem(row, 0, id_item)
                
                # 设置其他列
                self.table.setItem(row, 1, QTableWidgetItem(str(password['username'])))  # 用户名
                self.table.setItem(row, 2, QTableWidgetItem("********"))  # 掩码密码
                self.table.setItem(row, 3, QTableWidgetItem(str(password['url'] or "")))  # URL
                self.table.setItem(row, 4, QTableWidgetItem("未分类"))  # 分类 (数据库中没有此列)
                self.table.setItem(row, 5, QTableWidgetItem(str(password['notes'] or "")))  # 备注
                
            self.statusBar.showMessage(f"已加载 {len(passwords)} 条密码记录")
        except Exception as e:
            logging.error(f"加载密码时出错: {e}", exc_info=True)
            self.statusBar.showMessage(f"加载密码时出错: {str(e)}")
            self.table.setRowCount(0)
    
    def filter_passwords(self):
        """根据搜索条件过滤密码"""
        search_text = self.search_edit.text().lower()
        category = self.category_filter.currentText()
        
        for row in range(self.table.rowCount()):
            platform = self.table.item(row, 0).text().lower()
            username = self.table.item(row, 1).text().lower()
            url = self.table.item(row, 3).text().lower()
            item_category = self.table.item(row, 4).text()
            notes = self.table.item(row, 5).text().lower()
            
            # 检查是否匹配搜索文本
            text_match = (search_text in platform or 
                         search_text in username or 
                         search_text in url or 
                         search_text in notes)
            
            # 检查是否匹配分类
            category_match = (category == "所有分类" or category == item_category)
            
            # 如果同时匹配搜索文本和分类，则显示该行
            self.table.setRowHidden(row, not (text_match and category_match))
    
    def add_password(self):
        """添加新密码"""
        dialog = PasswordDialog(self)
        if dialog.exec():
            platform = dialog.platform_edit.text()
            username = dialog.username_edit.text()
            password = dialog.password_edit.text()
            url = dialog.url_edit.text()
            category = dialog.category_combo.currentText()
            notes = dialog.notes_edit.text()
            
            # 检查必填字段
            if not platform or not username or not password:
                QMessageBox.warning(self, "输入错误", "平台、用户名和密码为必填项")
                return
            
            # 添加到数据库
            password_id = self.db.add_password(platform, url, username, password, notes)
            
            # 更新表格
            row = self.table.rowCount()
            self.table.insertRow(row)
            
            # 设置密码ID为用户数据
            id_item = QTableWidgetItem(platform)
            id_item.setData(Qt.ItemDataRole.UserRole, password_id)
            self.table.setItem(row, 0, id_item)
            
            # 设置其他列
            self.table.setItem(row, 1, QTableWidgetItem(username))
            self.table.setItem(row, 2, QTableWidgetItem("********"))
            self.table.setItem(row, 3, QTableWidgetItem(url))
            self.table.setItem(row, 4, QTableWidgetItem(category))
            self.table.setItem(row, 5, QTableWidgetItem(notes))
            
            self.statusBar.showMessage(f"已添加密码: {platform}", 3000)
            
            # 重置自动锁定定时器
            self.reset_auto_lock_timer()
    
    def edit_password(self, row, column):
        """编辑密码"""
        # 获取密码ID
        password_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        
        # 从数据库获取密码详情
        password_data = self.db.get_password(password_id)
        
        if password_data:
            platform = password_data['platform']
            username = password_data['username']
            password = password_data['password']
            url = password_data['url']
            notes = password_data.get('notes', '')
            category = "未分类"  # 数据库中没有category字段，使用默认值
            
            # 打开编辑对话框
            dialog = PasswordDialog(self, password_id, platform, username, password)
            dialog.url_edit.setText(url)
            dialog.category_combo.setCurrentText(category)
            dialog.notes_edit.setText(notes)
            
            if dialog.exec():
                # 获取更新后的值
                new_platform = dialog.platform_edit.text()
                new_username = dialog.username_edit.text()
                new_password = dialog.password_edit.text()
                new_url = dialog.url_edit.text()
                new_category = dialog.category_combo.currentText()
                new_notes = dialog.notes_edit.text()
                
                # 检查必填字段
                if not new_platform or not new_username or not new_password:
                    QMessageBox.warning(self, "输入错误", "平台、用户名和密码为必填项")
                    return
                
                # 更新数据库
                self.db.update_password(password_id, new_platform, new_username, new_password, 
                                       new_url, new_category, new_notes)
                
                # 更新表格
                self.table.item(row, 0).setText(new_platform)
                self.table.item(row, 1).setText(new_username)
                self.table.item(row, 2).setText("********")
                self.table.item(row, 3).setText(new_url)
                self.table.item(row, 4).setText(new_category)
                self.table.item(row, 5).setText(new_notes)
                
                self.statusBar.showMessage(f"已更新密码: {new_platform}", 3000)
                
                # 重置自动锁定定时器
                self.reset_auto_lock_timer()
    
    def edit_selected_password(self):
        """编辑选中的密码"""
        selected_rows = self.table.selectionModel().selectedRows()
        if selected_rows:
            row = selected_rows[0].row()
            self.edit_password(row, 0)
        else:
            QMessageBox.information(self, "提示", "请先选择一个密码")
    
    def delete_selected_password(self):
        """删除选中的密码"""
        selected_rows = self.table.selectionModel().selectedRows()
        if not selected_rows:
            QMessageBox.information(self, "提示", "请先选择一个密码")
            return
        
        row = selected_rows[0].row()
        platform = self.table.item(row, 0).text()
        password_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        
        # 确认删除
        reply = QMessageBox.question(
            self, 
            "确认删除", 
            f"确定要删除 {platform} 的密码吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            # 从数据库删除
            self.db.delete_password(password_id)
            
            # 从表格删除
            self.table.removeRow(row)
            
            self.statusBar.showMessage(f"已删除密码: {platform}", 3000)
            
            # 重置自动锁定定时器
            self.reset_auto_lock_timer()
    
    def show_password_generator(self):
        """显示密码生成器对话框"""
        dialog = PasswordGeneratorDialog(self)
        if dialog.exec():
            # 获取生成的密码
            password = dialog.password_edit.text()
            
            # 复制到剪贴板
            pyperclip.copy(password)
            self.statusBar.showMessage("已生成密码并复制到剪贴板", 3000)
            
            # 设置剪贴板清除定时器
            clipboard_clear_after = self.settings.value('clipboard_clear_after', 30, type=int)
            if clipboard_clear_after > 0:
                self.clipboard_timer.start(clipboard_clear_after * 1000)
    
    def copy_username(self, row):
        """复制用户名到剪贴板"""
        username = self.table.item(row, 1).text()
        pyperclip.copy(username)
        self.statusBar.showMessage("已复制用户名到剪贴板", 3000)
    
    def copy_password(self, row):
        """复制密码到剪贴板"""
        # 获取密码ID
        password_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)
        
        # 从数据库获取密码
        password_data = self.db.get_password(password_id)
        if password_data:
            password = password_data['password']
            pyperclip.copy(password)
            self.statusBar.showMessage("已复制密码到剪贴板", 3000)
            
            # 设置剪贴板清除定时器
            clipboard_clear_after = self.settings.value('clipboard_clear_after', 30, type=int)
            if clipboard_clear_after > 0:
                self.clipboard_timer.start(clipboard_clear_after * 1000)
    
    def clear_clipboard(self):
        """清除剪贴板"""
        pyperclip.copy("")
        self.statusBar.showMessage("已清除剪贴板", 3000)
    
    def show_context_menu(self, position):
        """显示上下文菜单"""
        menu = QMenu(self)
        
        # 获取选中的行
        selected_rows = self.table.selectionModel().selectedRows()
        if not selected_rows:
            return
        
        row = selected_rows[0].row()
        
        # 添加菜单项
        copy_username_action = menu.addAction("复制用户名")
        copy_password_action = menu.addAction("复制密码")
        menu.addSeparator()
        edit_action = menu.addAction("编辑密码")
        delete_action = menu.addAction("删除密码")
        
        # 显示菜单并获取选择的操作
        action = menu.exec(self.table.mapToGlobal(position))
        
        # 处理选择的操作
        if action == copy_username_action:
            self.copy_username(row)
        elif action == copy_password_action:
            self.copy_password(row)
        elif action == edit_action:
            self.edit_password(row, 0)
        elif action == delete_action:
            self.delete_selected_password()
    
    def show_settings(self):
        """显示设置对话框"""
        dialog = SettingsDialog(self)
        if dialog.exec():
            # 应用设置
            self.load_settings()
            self.apply_theme()
            self.reset_auto_lock_timer()
    
    def load_settings(self):
        """加载设置"""
        # 设置默认值
        if not self.settings.contains('theme'):
            self.settings.setValue('theme', 'light')
        
        if not self.settings.contains('auto_lock_after'):
            self.settings.setValue('auto_lock_after', 5)  # 5分钟
        
        if not self.settings.contains('clipboard_clear_after'):
            self.settings.setValue('clipboard_clear_after', 30)  # 30秒
    
    def reset_auto_lock_timer(self):
        """重置自动锁定定时器"""
        auto_lock_after = self.settings.value('auto_lock_after', 5, type=int)
        if auto_lock_after > 0:
            self.auto_lock_timer.start(auto_lock_after * 60 * 1000)  # 转换为毫秒
    
    def lock_application(self):
        """锁定应用程序"""
        # TODO: 实现锁定功能
        pass
    
    def apply_theme(self):
        """应用主题样式"""
        theme = self.settings.value('theme', 'light')
        self.style_manager.apply_theme(self, theme)
    
    def import_passwords(self):
        """导入密码"""
        # TODO: 实现导入功能
        pass
    
    def export_passwords(self):
        """导出密码"""
        # TODO: 实现导出功能
        pass
    
    def analyze_passwords(self):
        """分析密码"""
        # TODO: 实现密码分析功能
        pass
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(
            self,
            "关于密码管理器",
            "密码管理器 v1.0\n\n"
            "一个安全、易用的密码管理工具\n\n"
            "© 2023 密码管理器团队"
        )

def main():
    """主函数"""
    # 配置日志
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler()
        ]
    )
    
    # 加载环境变量
    load_dotenv()
    
    # 创建应用程序
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    
    # 创建主窗口
    window = MainWindow()
    window.show()
    
    return app, window

def run():
    """运行应用程序"""
    app, window = main()
    return app.exec()

if __name__ == '__main__':
    run()